# -*- encoding：utf-8 -*-
import os
from time import sleep
import re


def switchTo(path):
    os.chdir(path)
    print(f"recent path has switched to {path}")


def makeDir(path):
    if not os.path.exists(path):
        os.makedirs(path)


def makeDirAndSwitch(path):
    makeDir(path)
    switchTo(path)


def makeFile(path):
    if not os.path.exists(path):
        with open(path, "w", encoding="utf-8") as f:
            pass
        print(f"new file {path}")


def alterFileLine(file, old_str, new_str):
    # replace the line containing 'old_str' with 'new_str'
    with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
        for line in f1:
            if old_str in line:
                f2.write(new_str)
            else:
                f2.write(line)
    os.remove(file)
    os.rename("%s.bak" % file, file)

# 生成格式化的文件
root = os.getcwd()
print(f'now at {root}')
studentId = input('请输入你的学号：')
makeDirAndSwitch('../SUIBEER_Students')
makeDirAndSwitch(rf'./student_{studentId}')
makeFile("start.bat")
makeFile("demand.json")
makeFile("student_infor.json")
makeDirAndSwitch("courses")
makeFile("courses.sqlite3")
switchTo(root)

# 修改Django配置文件，使得服务器使用本学生文件夹数据库
alterFileLine(
    './Django/SUIBEER/SUIBEER/settings.py',
    "'NAME': BASE_DIR",
    f"        'NAME': BASE_DIR / '../../../SUIBEER_Students/student_{studentId}/courses/courses.sqlite3',\n"
)

# 通过爬虫获取当前学生的教学方案


# 编写教务处要求文档 command.json

# 获取当前学生4年内已有的备选课表，按照“学年_学期”命名存储在courses

# 遍历课表，存储至数据库

# 输出校验信息以供确认

# 写入启动文件到student的start.bat(我把他放到最后一步，别问为什么，问就是为了万无一失）
switchTo(rf'../SUIBEER_Students/student_{studentId}')
with open("start.bat", 'w', encoding="utf-8") as f:
    f.write(f'cd ../../SUIBEER_main\npython ./main.py {studentId}')
# 结束
pass
